package org.example.netty.handler;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

/**
 * 处理器多SocketChannel共享
 */
@ChannelHandler.Sharable
public class EchoServerHandler extends ChannelInboundHandlerAdapter {
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {

        ByteBuf buf = (ByteBuf) msg;
        int length = buf.readableBytes();
        byte[] contents = new byte[length];
        buf.readBytes(contents);
        System.out.println("接收服务端消息：" + new String(contents));

        // 回写内容
        ByteBuf buffer = ctx.alloc().buffer();
        buffer.writeBytes("欢欢，你好".getBytes());
        ctx.writeAndFlush(buffer);

        // 调用父内容进行buf的释放
        super.channelRead(ctx, msg);
    }
}
